package com.example.wan_android.viewmodel

import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.wan_android.http.code.UserRepository
import com.example.wan_android.tools.Sp
import com.example.wan_android.ui.activity.RegisterActivity
import kotlinx.coroutines.launch


class LoginViewModel : BaseViewModel() {
    var context: Context? = null
    private val _showPassword = MutableLiveData<Boolean>(false)
    val showPassword: MutableLiveData<Boolean> = _showPassword
    private val _currentPosition = MutableLiveData<Int>(0)
    val currentPosition = _currentPosition


    fun setShowPassword(
    ) {
        _showPassword.value = !(_showPassword.value ?: false)
    }

    fun setCurrentPosition(index: Int) {
        _currentPosition.value = index
    }

    fun jumpRegisterActivity() {
        startActivity(Intent(), targetClass = RegisterActivity::class.java)
    }

    fun firstLogin(userName: String, password: String) {
        viewModelScope.launch {
            UserRepository().fetchLoginUserData(userName, password).onSuccess {
                Sp.setString(context!!, "userName", userName)
                Sp.setString(context!!, "password", password)
                Toast.makeText(context, "登录成功!", Toast.LENGTH_SHORT).show()
                finishActivity()
            }.onFailure {
                Log.i("TAG", "login: " + it)
                Toast.makeText(context, "登录失败!", Toast.LENGTH_SHORT).show()
            }
        }
    }
}